<template>
  <div class="article-meta">
    <nuxt-link :to="{ name: 'profile', params: { username: article.author.username } }">
      <img :src="article.author.image" />
    </nuxt-link>
    <div class="info">
      <nuxt-link
        class="author"
        :to="{ name: 'profile', params: { username: article.author.username } }"
      >{{ article.author.username }}</nuxt-link>
      <span class="date">{{ article.createdAt | date('MMM DD, YYYY') }}</span>
    </div>
    <button
      class="btn btn-sm btn-outline-secondary" 
      :class="{ active: article.author.following }"
      @click="onFollow"
    >
      <i class="ion-plus-round"></i>
      &nbsp;
      {{ article.author.following ? 'unFollow' : 'Follow' }} {{ article.author.username }}
    </button>
    &nbsp;&nbsp;
    <button
      class="btn btn-sm btn-outline-primary"
      :class="{ active: article.favorited, disabled: article.favoriteDisabled }"
      @click="onFavorite"
      :disabled="article.favoriteDisabled"
    >
      <i class="ion-heart"></i>
      &nbsp;
      {{ article.favorited ? 'unFavorite' : 'Favorite' }} Article
      <span class="counter">{{ `(${article.favoritesCount})` }}</span>
    </button>
  </div>
</template>

<script>
import { followUser, unFollowUser } from '@/api/profile'
import { addFavorite, deleteFavorite } from "@/api/article";

export default {
  props: {
    article: {
      type: Object,
      required: true,
    },
  },
  methods: {
    async onFollow() {
      const action = this.article.author.following ? unFollowUser : followUser;
      const { data } = await action(this.article.author.username);
      this.article.author.following = data.profile.following;
    },
    async onFavorite() {
      this.article.favoriteDisabled = true;
      const action = this.article.favorited ? deleteFavorite : addFavorite;
      const { data } = await action(this.article.slug);
      this.article.favorited = data.article.favorited;
      this.article.favoritesCount = data.article.favoritesCount;
      this.article.favoriteDisabled = false;
    }
  }
};
</script>

<style>
</style>